package com.hongdee.rbac.interceptor;

import com.alibaba.fastjson.JSON;
import com.hongdee.base.Constant;
import com.hongdee.base.entity.ResultEntity;
import com.hongdee.common.util.TokenUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 名  称:
 * 类  型: class
 * 描  述: 拦截登陆信息
 * 路  径:com.hongdee.base.interceptor
 * 作  者:liuze
 * 日  期:2017/2/4 08:58
 */
public class LoginInterceptor implements HandlerInterceptor {
    private Log logger = LogFactory.getLog(this.getClass());
    private StringRedisTemplate template;

    /**
     * 方法名称:preHandle
     * 方法描述: 重新实现请求拦截，handler 为 Spring的 Controller
     * 参数名称: HttpServletRequest
     * 参数名称: HttpServletResponse
     * 返回内容: Object handler
     * 异常说明:
     * 创建用户:
     * 创建时间:
     * 修改用户:
     * 修改时间:
     * 修改内容:
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("处理请求登陆判断");
        if (template == null) {
            //该处无法自动注入，主动从spring中获取
            BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
            template = factory.getBean(StringRedisTemplate.class);
            //loginService = factory.getBean(LoginServiceImpl.class);
        }
        String token = request.getParameter(Constant.TOKEN_KEY);
        String uid = request.getParameter("uid");
        //校验是否传递登录验证参数
        if (StringUtils.isEmpty(uid) || StringUtils.isEmpty(token)) {
            unLogin(request, response, handler);
            return false;
        }

        //检查登陆信息，判断是否登陆状态
        //从redis取token信息查看是否存在
        String loginToken = TokenUtil.getToken(uid);
        if (!loginToken.equals(token)) {
            unLogin(request, response, handler);
            return false;
        }
        /*****
         * 当前用户是否具有调用当前 URL的权限，排除固定的权限
         * 暂不实现
         */

        return true;
    }

    //请求之后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    //请求处理完成时处理
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //请求内部处理完毕，删除uKey信息
        request.removeAttribute(Constant.SESSION_KEY);
    }

    /**
     * 方法名称:unLogin
     * 方法描述: 返回未登录信息
     * 返回内容:
     * 异常说明:
     * 创建用户:
     * 创建时间:
     * 修改用户:
     * 修改时间:
     * 修改内容:
     */
    private void unLogin(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ResultEntity re = new ResultEntity();
        re.setSuccess(false);
        re.setMsg("您还未登录，请先登录");
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        re.setExType("unLogin");
        PrintWriter pw = response.getWriter();
        pw.write(JSON.toJSONString(re));
        pw.flush();
        pw.close();
    }

    /**
     * 方法名称:unLogin
     * 方法描述: 返回无权限信息
     * 返回内容:
     * 异常说明:
     * 创建用户:
     * 创建时间:
     * 修改用户:
     * 修改时间:
     * 修改内容:
     */
    private void unAuth(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ResultEntity re = new ResultEntity();
        re.setSuccess(false);
        re.setMsg("您不具备访问权限，请联系管理员！");
        re.setExType("unAuth");
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        PrintWriter pw = response.getWriter();
        pw.write(JSON.toJSONString(re));
        pw.flush();
        pw.close();
    }
}
